<template>
  <div>
    <RePage>
      <MyFormCreate :clear-event="getTableList" v-model="searchForm" :rule="searchFormRules" :key="key">
        <template #field-createdAt="scope">
          <el-form-item>
            <el-date-picker type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
              value-format="YYYY-MM-DD" placeholder="请选择创建时间" style="width: 100%" v-model="searchForm.createdAt"
              @change="dateChange" />
          </el-form-item>
        </template>
        <template #field-productId="scope">
          <el-select clearable @clear="getTableList" v-model="searchForm.productId" placeholder="请选择产品名称"
            @change="v => scope.data.model.callback(v)">
            <el-option v-for="item in productTypes" :key="item.productId" :label="item.productName"
              :value="item.productId"></el-option>
          </el-select>
        </template>
        <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>

        <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
      </MyFormCreate>
      <div>
        <el-button v-auth="'business.alarm.alarm.export'" type="primary" @click="importAll">导出</el-button>
        <el-button v-auth="'business.alarm.alarm.remove'" type="danger" :disabled="!chosedevis.length" @click="deletes()">批量删除</el-button>
      </div>
      <pure-table class="mt-5" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)" :isShowPag="false" showOverflowTooltip
        showSelection @selection-change="selechange">
        <template #dealStatus="{ row }">
          <el-tag :type="HANDLESTATUSTEXT[row.dealStatus]?.type" :key="row.dealStatus">{{
            HANDLESTATUSTEXT[row.dealStatus]?.label }}</el-tag>
          <!-- {{ isNullOrEmpty( HANDLESTATUSTEXT[row.dealStatus]?.label ) }} -->
        </template>
        <template #confirm="{ row }">
          <el-tag :type="CONFIRMSTATUSTEXT[row.confirm]?.type" :key="row.confirm">{{
            CONFIRMSTATUSTEXT[row.confirm]?.label }}</el-tag>
          <!-- {{ isNullOrEmpty( CONFIRMSTATUSTEXT[row.confirm]?.label ) }} -->
        </template>

        <template #alarmType="{ row }">
          <el-tag :type="ALARMTYPES[row.alarmType]?.type" :key="row.alarmType">{{ ALARMTYPES[row.alarmType]?.label
            }}</el-tag>
          <!-- {{ isNullOrEmpty( ALARMTYPES[row.alarmType]?.label ) }} -->
        </template>
        <template #action="{ row }">
          <el-space>
            <sj-link custom-type="sblue" :underline="false" @click="info(row)">查看</sj-link>
            <sj-link v-auth="'business.alarm.alarm.remove'" custom-type="sred" :underline="false"
              @click="deletes(row)">删除</sj-link>
          </el-space>
        </template>
      </pure-table>
      <div class="mt-5">
        <el-pagination v-model:current-page="searchForm.page" v-model:page-size="searchForm.limit" background
          :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList" @current-change="getTableList" />
      </div>
    </RePage>
  </div>
</template>
<script lang="ts" setup>
import {isNullOrEmpty,initPureTableConfig} from '@/utils/functions'
import alarminfo from "./alarm-info.vue";
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import RePage from "@/components/RePage/index.vue";
import ReTable from "@/components/ReTable/index.vue";
import editForm from "./form.vue";
import { reactive, ref, h } from "vue";
import { PAGE_LAYOUT } from "@/constant";
import {
  CONFIRMSTATUS,
  CONFIRMSTATUSTEXT,
  HANDLESTATUSTEXT,
  HANDLESTATUS,
  ALARMTYPE,
  ALARMTYPES
} from "@/constant/alarm-mangenment";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getList,
  getInfo,
  addInfo,
  editInfo,
  deleteInfo,
  exportalarms,
  getProductType,
  importAllalarm
} from "@/api/operate/alarm-management/alarm-log/index";
import { titles, defaultSearchForm, prompt, defaultInfoForm } from "./index";
import { addDialog } from "@/components/ReDialog";
import {
  cloneDeep,
  isAllEmpty,
  deviceDetection,
  debounce
} from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customDebounce, customPromiseDebounce } from "@/utils/functions";
const route = useRoute()  // 获取路由参数
const productTypes = ref([]);
const centerDialogVisible = ref(false);
const searchForm = ref(defaultSearchForm());
const key = ref(0);
const showInfo = ref();
const formRef = ref();
const tableData = reactive({
  data: [],
  total: 0
});
//复选框选择的内容
const chosedevis = ref([]);
const searchFormRules = [
  {
    type: "fieldComponent",
    field: "productId",
    title: titles.productName,
    options: productTypes,
    props: {
      placeholder: prompt.productName,
      clearable: true
    }
  },
  {
    type: "input",
    field: "deviceSN",
    title: titles.deviceSN,
    value: null,
    props: {
      placeholder: prompt.deviceSN,
      clearable: true
    }
  },
  {
    type: "input",
    field: "alarmTitle",
    title: titles.alarmTitle,
    value: null,
    props: {
      placeholder: prompt.alarmTitle,
      clearable: true
    }
  },
  {
    type: "select",
    field: "confirm",
    title: titles.confirm,
    value: null,
    options: CONFIRMSTATUS,
    props: {
      placeholder: prompt.confirm,
      clearable: true
    }
  },
  {
    type: "select",
    field: "alarmType",
    title: titles.alarmType,
    value: null,
    options: ALARMTYPE,
    props: {
      placeholder: prompt.alarmType,
      clearable: true
    }
  },
  {
    type: "select",
    field: "dealStatus",
    title: titles.dealStatus,
    options: HANDLESTATUS,
    value: null,
    props: {
      placeholder: prompt.dealStatus,
      clearable: true
    }
  },
  {
    type: "fieldComponent",
    field: "createdAt",
    title: titles.createdAt,
    value: null,
    props: {
      placeholder: prompt.createdAt,
      clearable: true
    }
  },
  { type: "number", field: "page", title: "page", hidden: true },
  { type: "number", field: "limit", title: "limit", hidden: true }
];

const roleTableConfig = [
  { type: "selection", align: "left", fixed: 'left' },
  { prop: "id", label: titles.id, width:  100, fixed: 'left' },
  { prop: "unityName", label: "所属单位", minWidth: 150 },
  { prop: "place", label: titles.place, minWidth: 100 },
  { prop: "projectName", label: titles.projectName, minWidth: 150 },
  { prop: "productName", label: titles.productName, minWidth: 100 },
  { prop: "deviceSN", label: titles.deviceSN, minWidth: 100 },
  { prop: "alarmTitle", label: titles.alarmTitle, minWidth: 100 },
  { slot: "confirm", label: titles.confirm, minWidth: 90 },
  { slot: "alarmType", label: titles.alarmType, minWidth: 90 },
  { slot: "dealStatus", label: titles.dealStatus, minWidth: 100 },
  { prop: "createdAt", label: titles.createdAt, minWidth: 120 },
  { prop: "lastAlarmTime", label: "最后更新时间", minWidth: 120 },
  { slot: "action", label: titles.action, width: 90, fixed: "right" }
];
onMounted(() => {
  if (route.query.confirm) {
    searchForm.value.confirm =Number(route.query.confirm)
    key.value++
  }else if(route.query.dealStatus){
    searchForm.value.dealStatus = Number(route.query.dealStatus)
    key.value++
  }
  getTableList();
  getProductType().then(res => {
    if (res.code === 200) {
      productTypes.value = res.result;
      key.value++;
    }
  });
});


//导出全部
const importAll = () => {
  importAllalarm(searchForm.value).then(res => {
    let fileName = "告警记录.xlsx"
    if (res.type === "text/csv") {
      fileName = "告警记录.csv"
    }
    const url = window.URL.createObjectURL(res)
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    link.remove()
  })
}
const dateChange = e => {
  searchForm.value.startTime = e[0];
  searchForm.value.endTime = e[1];
};
// 获取列表数据
const getTableList = () => {
  getList(searchForm.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  });
};
// 重置搜索栏
const resetting = () => {
  //点击重置按键
  Object.assign(searchForm.value, defaultSearchForm());
  key.value++;
  getTableList();
};
// 详情
const info = row => {
  // centerDialogVisible.value = true;
  addDialog({
    title: `告警详情`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    props: {
      id: row.deviceId
    },
    hideFooter: true,
    closeOnClickModal: false,
    contentRenderer: () => h(alarminfo, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: true,
        id: row.id,
        deviceId: row.deviceId,
        formInline: defaultInfoForm()
      };
      getInfo({ id: row.id }).then(res => {
        if (res.code == 200) {
          options.props.formInline = res.result;
        }
        options.props.isLoading = false;
      });
    },
    close: () => {
      getTableList();
    }
  });
};
// 新增
const add = row => {
  showInfo.value = {};
  openDialog();
};
// 删除
const deletes = (row?) => {
  ElMessageBox.confirm("您确定要删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    console.log(chosedevis.value.length, "3333");
    deleteInfo({
      alarmIds: row ? [row.id] : chosedevis.value.map(item => item.id)
    }).then(res => {
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        getTableList();
      }
    });
  });
};
// 开启弹窗
const openDialog = () => {
  exportalarms().then(res => {
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: res.msg
      });
    } else {
      ElMessage({
        type: "error",
        message: res.msg
      });
    }
  });
};
//表格复选框选择事件
const selechange = data => {
  chosedevis.value = data;
};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
</script>
<style lang="scss" scoped></style>
